package com.universal_library.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.jph.takephoto.app.TakePhotoFragment;
import com.universal_library.utils.ImageLoader;

import butterknife.ButterKnife;

/**
 * Created by solin on 2018/1/29.
 */

public abstract class BaseFragment extends TakePhotoFragment {
    protected Context mContext;
    protected Bundle mBundle;
    protected View mRoot;
    protected RequestManager mImageLoader;
    protected LayoutInflater mInflater;
    protected RequestManager mImageLoder;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBundle = getArguments();
        initBundle(mBundle);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRoot != null) {
            ViewGroup parent = (ViewGroup) mRoot.getParent();
            if (parent != null) {
                parent.removeView(mRoot);
            }
        } else {
            mRoot = inflater.inflate(getLayoutId(), container, false);
            mInflater = inflater;
            onBindViewBefore(mRoot);
            ButterKnife.bind(this, mRoot);
            initView(mRoot);
        }
        initData();
        return mRoot;
    }

    public void initBundle(Bundle mBundle) {
        if (mBundle == null)
            return;
    }

    protected abstract int getLayoutId();

    protected abstract void initView(View view);

    protected abstract void initData();

    protected void onBindViewBefore(View view) {

    }

    public boolean onBackPressed() {
        return false;
    }

    /*********加载网络图片*********/
    public synchronized RequestManager getImageLoader() {
        if (mImageLoder == null)
            mImageLoder = Glide.with(this);
        return mImageLoder;
    }

    /**
     * 加载挽留过图片
     *
     * @param viewId
     * @param url
     */
    protected void setImageFromNet(ImageView viewId, String url) {
        setImageFromNet(viewId, url, 0);
    }

    /**
     * 网络图片错误显示本地图片
     *
     * @param viewId 控件id
     * @param url    网络图片url
     * @param resId  本地资源url
     */
    protected void setImageFromNet(ImageView viewId, String url, int resId) {
        ImageLoader.loadImage(getImageLoader(), viewId, url, resId);
    }
}
